
package com.naza.rpc.netty.handler;

import com.naza.rpc.netty.RpcReceiveHandler;
import com.naza.rpc.serialize.MessageCodecUtil;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.util.Map;

/**
 * RPC服务端  jdk 编解码  处理(RpcReceiveHandler)
 * @author yl
 */
public class JdkNativeRecvHandler implements NazaRecvHandler {
    @Override
    public void handle(Map<String, Object> handlerMap, ChannelPipeline pipeline) {
        // ObjectDecoder的基类半包解码器LengthFieldBasedFrameDecoder的报文格式保持兼容，
        // 因为底层的父类LengthFieldBasedFrameDecoder的初始化参数即为super(maxObjectSize,0,4,0,4);
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,
                MessageCodecUtil.MESSAGE_LENGTH, 0, MessageCodecUtil.MESSAGE_LENGTH));
        // 利用LengthFieldPrepender回填补充ObjectDecoder的消息报文头
        pipeline.addLast(new LengthFieldPrepender(MessageCodecUtil.MESSAGE_LENGTH));
        pipeline.addLast(new ObjectEncoder());
        // 考虑到并发性能，采用weakCachingConcurrentResolver缓存策略，一般情况使用:cacheDisable即可
        pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE,
                ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
        pipeline.addLast(new RpcReceiveHandler(handlerMap));
    }
}
